<template>
  <div class="wrapper">
    <div class="home-section">
      <div class="header">
        <el-select
          v-model="selectedModel"
          style="width: 120px; background: transparent"
          popper-class="select-dropdown"
          @change="handleModelChange"
        >
          <template #header>
            <div style="color: #333; font-size: 12px; text-align: center">
              选择模型:
            </div>
          </template>
          <el-option
            v-for="item in options"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          />
        </el-select>
      </div>
      <div class="logo">
        <el-icon
          style="color: var(--el-color-primary)"
          size="64"
          class="logo-icon"
        >
          <Smart />
        </el-icon>
        <h1>高校大模型应用平台</h1>
      </div>
      <div class="main-content">
        <Section
          title="智能体应用"
          desc="提升办公学习效率，就用宇智AI！"
          :items="dataList"
          :loading="loading"
          @click="useApp"
        >
          <template #header-afterfix v-if="totalPage > query.limit">
            <el-icon
              size="24"
              color="#666"
              style="cursor: pointer"
              @click="handleRefresh"
            >
              <Refresh />
            </el-icon>
          </template>
        </Section>
        <Section
          title="知识库"
          desc="随时随地提问解答，不断提升自我！"
          :items="knowledgeList"
          :loading="knowledgeLoading"
          attr="name"
          descLabel="description"
          @click="useKnowledge"
        >
          <template
            #header-afterfix
            v-if="knowledgeTotal > knowledgeQuery.limit"
          >
            <el-icon
              size="24"
              color="#666"
              style="cursor: pointer"
              @click="refreshKnowledge"
            >
              <Refresh />
            </el-icon>
          </template>
        </Section>
        <div class="feature-cards">
          <div class="feature-card" @click="router.push('/study/project')">
            <div class="ai-study">
              <el-icon
                style="color: var(--el-color-primary)"
                size="64"
                class="ai-icon"
              >
                <Study />
              </el-icon>
              <div class="feature-title">
                <el-icon size="18" class="robot"> <AIRobot /> </el-icon>AI学习
              </div>
            </div>
          </div>
          <div class="feature-card" style="margin-top: 10px">
            <div class="carousel" style="width: 100%">
              <el-carousel
                indicator-position="outside"
                height="180px"
                style="width: 100%"
              >
                <el-carousel-item v-for="item in swiperItems" :key="item.path">
                  <div
                    style="
                      flex-direction: column;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                      width: 100%;
                      height: 100%;
                      gap: 20px;
                    "
                    class="carousel-item"
                  >
                    <el-icon
                      style="color: var(--el-color-primary)"
                      size="84"
                      class="no-inherit"
                    >
                      <Component :is="item.icon"></Component>
                    </el-icon>
                    <div
                      class="btn-ai-card"
                      style="width: 100%; margin-top: 20px"
                      @click="router.push(item.path)"
                    >
                      <el-icon size="18" class="robot">
                        <AIRobot />
                      </el-icon>
                      {{ item.name }}
                    </div>
                  </div>
                </el-carousel-item>
              </el-carousel>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <Scroller
        width="100%"
        :buttons="questions"
        @click="selectQuestionTemplate"
      ></Scroller>
      <div class="input-box question-input-inner-wrapper">
        <el-input
          type="textarea"
          v-model="askQuestion"
          placeholder="提出您希望助手为您完成事情...（Enter = 发送，Shift+Enter = 换行）"
          show-word-limit
          resize="none"
          :input-style="{
            border: 'none !important',
            height: '100%',
          }"
          :rows="2"
          class="custom-scrollbar"
          maxlength="1000"
          @keydown.enter="handleKeyCode($event)"
        />
        <el-button
          type="primary"
          :disabled="askQuestion && !askQuestion.trim()"
          :icon="Send"
          @click="handleSend"
          circle
        />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onBeforeMount, ref, reactive, shallowRef } from 'vue'
import Scroller from './scroller.vue'
import Smart from '@/icons/smart.vue'
import Study from '@/icons/Study.vue'
import Send from '@/icons/Send.vue'
import Section from './components/section.vue'
import Note from '@/icons/Note.vue'
import PptxFilled from '@/icons/PptxFilled.vue'
import AIRobot from '@/icons/AIRobot.vue'
import { httpAppList } from '@/api/application.js'
import { httpKnowledgeList } from '@/api/knowledge.js'
import { debounce } from '@/utils/tools'
import { useRouter } from 'vue-router'
import useAppStore from '@/stores/application.js'
import useKnowledgeStore from '@/stores/knowledge.js'
import { httpTemplateList } from '@/api/templates.js'
import Analysis from '@/icons/Analysis.vue'
import useChat from '@/stores/chat.js'
import Meeting from '@/icons/Meeting.vue'
import { storeToRefs } from 'pinia'
import { httpModels } from '@/api/chat.js'
import { CHAT_MODEL } from '@/enum/study'

const { question } = storeToRefs(useChat())
const knowledgeStore = useKnowledgeStore()
const router = useRouter()
const appStore = useAppStore()
const askQuestion = ref('')
const swiperItems = [
  {
    path: '/ai-ppt',
    name: 'AI PPT',
    color: 'blue',
    icon: PptxFilled,
  },
  {
    path: '/course/list',
    name: 'AI 课程解析',
    color: '#534ad1',
    icon: Analysis,
  },
  {
    path: '/file/note',
    name: 'AI 笔记',
    color: '#175cff',
    icon: Note,
  },
  {
    path: '/meeting/record',
    name: 'AI 会议',
    color: '#175cff',
    icon: Meeting,
  },
]
const selectedModel = ref('openchat')
const options = ref<any>([])
const handleModelChange = () => {
  localStorage.setItem(CHAT_MODEL.GENERAL, selectedModel.value)
}

const query = reactive({
  classification_id: 0,
  knowledge_id: 0,
  page: 1,
  limit: 3,
  keyword: '',
  is_owner: 0,
})

const handleKeyCode = (e) => {
  if (e.keyCode === 13) {
    if (!e.shiftKey) {
      e.preventDefault()
      handleSend()
    }
  }
}
const handleSend = () => {
  question.value = (askQuestion.value && askQuestion.value.trim()) || ''
  if (question.value) {
    router.push('/chat?add=1')
  }
}

const loading = ref(false)
const dataList = ref([])
const listTotal = ref(0)
const totalPage = ref(1)
const getList = async () => {
  loading.value = true
  const query_data = { ...query }
  if (query_data.classification_id < 0) {
    query_data.classification_id = 0
  }
  const response = await httpAppList(query_data).catch(() => null)
  loading.value = false
  if (!response) return
  const { list, total } = response
  dataList.value = list
  listTotal.value = total
  totalPage.value = Math.ceil(total / query_data.limit)
}
const knowledgeList = ref([])
const knowledgeTotal = ref(0)
const knowledgeQuery = reactive({
  sort_id: 0,
  page: 1,
  keyword: '',
  limit: 3,
})
const knowledgeLoading = ref(false)
const knowledgeTotalPage = ref(1)
const getKnowledgeList = async () => {
  knowledgeLoading.value = true
  const response = await httpKnowledgeList(knowledgeQuery)
    .catch(() => null)
    .finally(() => {
      knowledgeLoading.value = false
    })
  if (!response) return
  const { list, total } = response
  knowledgeList.value = list
  knowledgeTotal.value = total
  knowledgeTotalPage.value = Math.ceil(total / knowledgeQuery.limit)
}
const handleRefresh = debounce(() => {
  if (query.page < totalPage.value) {
    query.page++
    getList()
  } else {
    query.page = 1
    dataList.value = []
    getList()
  }
}, 500)
const refreshKnowledge = debounce(() => {
  if (knowledgeQuery.page < knowledgeTotalPage.value) {
    knowledgeQuery.page++
    getKnowledgeList()
  } else {
    knowledgeQuery.page = 1
    knowledgeList.value = []
    getKnowledgeList()
  }
}, 500)
const useApp = (item) => {
  const itemNew = { ...item }
  itemNew.option_message = JSON.parse(itemNew.option_message)
  appStore.setUseApp(itemNew)
  router.push('/chat?add=1')
}
const useKnowledge = (item) => {
  if (knowledgeStore.getKnowledge().id === item.id) {
    knowledgeStore.setKnowledge(0, '')
  } else {
    knowledgeStore.setKnowledge(item.id, item.name)
    router.push('/chat?add=1')
  }
}
const q_loading = ref(false)
const questions = ref([])
const getQuestions = () => {
  q_loading.value = true
  httpTemplateList({
    label_id: 0,
    knowledge_id: 0,
    page: 1,
    limit: 6,
  })
    .then(({ list, total }: any) => {
      q_loading.value = false
      questions.value = list
    })
    .catch(() => {
      q_loading.value = false
    })
}
const selectQuestionTemplate = (item) => {
  askQuestion.value = item.template
}
const getModels = async () => {
  const models: any = await httpModels()
  if (models) {
    options.value = models.list || []
  }
}
onBeforeMount(() => {
  getList()
  getKnowledgeList()
  getQuestions()
  getModels()
  selectedModel.value = localStorage.getItem(CHAT_MODEL.GENERAL) || 'openchat'
})
</script>
<style scoped lang="scss">
.wrapper {
  // min-width: 1000px;
  min-height: 650px;
  height: 100%;
  display: flex;
  width: 100%;
  flex-direction: column;
  justify-content: space-between;
  // background: linear-gradient(to top, #f8f9fa, #edbb8f);
  .home-section {
    height: calc(100% - 120px);
    flex-shrink: 0;
    .el-select {
      background-color: transparent !important;
      :deep(.el-select__wrapper) {
        background-color: rgba($color: #fff, $alpha: 0.1);
        border: none;
        box-shadow: none;
      }
    }
  }
  .header {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    // margin-bottom: 10px;
  }

  .logo {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    height: 80px;
    margin-bottom: 10px;
    .logo-icon:hover {
    }
  }

  .logo h1 {
    font-size: 24px;
    color: #333;
    font-weight: 600;
  }

  .menu-button {
    padding: 8px 15px;
    background: white;
    border-radius: 5px;
    cursor: pointer;
  }

  .main-content {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    margin-bottom: 10px;
    max-width: 800px;
    margin: 0 auto;
  }

  .feature-cards {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    min-height: 200px;
    max-height: 400px;
    cursor: pointer;
  }
  .feature-card {
    background: rgba($color: #fff, $alpha: 0.5);
    border-radius: 15px;
    padding: 20px;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .ai-study {
      width: 100%;
    }
    &:hover {
      .ai-icon {
        transform: scale(1.1);
        transition: transform 0.2s ease-in-out;
      }
      .feature-title {
        background-color: var(--el-button-hover-bg-color) !important;
        border-color: var(--el-color-primary) !important;
        color: var(--el-color-primary) !important;
      }
    }
    .carousel {
      &:hover {
        .btn-ai-card {
          background-color: var(--el-button-hover-bg-color) !important;
          border-color: var(--el-color-primary) !important;
          color: var(--el-color-primary) !important;
        }
        .robot {
          color: var(--el-color-primary) !important;
        }
      }
    }
    .carousel-item {
      .btn-ai-card {
        border: 1px solid var(--el-border-color);
        background-color: var(--el-bg-color);
        border-radius: 15px;
        font-size: 12px;
        padding: 6px 0px;
        height: 32px;
        color: var(--el-text-color-primary);
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 4px;
      }
    }
  }

  .feature-icon {
    width: 48px;
    height: 48px;
    margin-bottom: 10px;
  }

  .feature-title {
    width: 100%;
    font-size: 16px;
    color: #333;
    border: 1px solid var(--el-border-color);
    background-color: var(--el-bg-color);
    border-radius: 15px;
    font-size: 12px;
    padding: 6px 0px;
    height: 32px;
    color: var(--el-text-color-primary);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
  }
  .footer {
    height: 120px;
    display: flex;
    flex-direction: column;
    flex-shrink: 0;
    justify-content: center;
    align-items: center;
  }
  .input-box {
    height: 60px;
    width: 100%;
    max-width: 800px;
    display: flex;
    align-items: center;
    border-radius: 20px;
    padding: 12px 20px;
    background-color: #fff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    :deep(.el-textarea__inner) {
      border: none;
      box-shadow: none;
    }
  }

  .input-box input {
    flex: 1;
    border: none;
    outline: none;
    font-size: 14px;
    background-color: transparent;
    padding: 8px;
  }
}
</style>

<style lang="scss">
.question-input-inner-wrapper {
  /* 针对el-input的textarea类来修改滚动条 */
  .el-textarea__inner::-webkit-scrollbar {
    width: 10px !important; /* 设置滚动条的宽度 */
    height: 10px !important; /* 设置水平滚动条的高度 */
  } /* 滚动条轨道 */
  .el-textarea__inner::-webkit-scrollbar-track {
    background: #f1f1f1 !important; /* 滚动条轨道背景 */
    border-radius: 10px !important;
  } /* 滚动条滑块 */
  .el-textarea__inner::-webkit-scrollbar-thumb {
    background: #e6e6e6 !important; /* 滚动条滑块颜色 */
    border-radius: 10px !important;
  } /* 滚动条滑块悬停时的效果 */
  .el-textarea__inner::-webkit-scrollbar-thumb:hover {
    background: #555 !important; /* 鼠标悬停时的颜色 */
  }
  .el-textarea__inner::placeholder {
    // position: relative;
    // vertical-align: middle !important;
  }
}
</style>
